package cyan.gf.sql;

import cyan.gf.control.SimpleTreeItem;
import cyan.gf.db.CrudInstance;
import cyan.gf.db.TableField;
import cyan.gf.field.FieldWarpper;
import cyan.gf.field.OracleFieldWarpper;
import cyan.gf.tree.TreeLeaf;
import javafx.scene.control.TreeItem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cyan on 2017/3/3.
 * Email:qsyan@vip.qq.com
 */
public class OracleDao {

  CrudInstance crudInstance;

  public OracleDao(CrudInstance crudInstance) {
    this.crudInstance = crudInstance;
  }

  public List<TreeItem<SimpleTreeItem>> loadTables() {
    List<TreeItem<SimpleTreeItem>> treeItems = new ArrayList<>();
    String query = "select table_name from user_tables";
    crudInstance.eachRow(query, rs -> {
      SimpleTreeItem simpleTreeItem = new SimpleTreeItem(rs.getString(1), "/images/tree_table.png");
      simpleTreeItem.setMessage(TreeLeaf.TABLE);
      treeItems.add(new TreeItem<>(simpleTreeItem));
    });
    return treeItems;
  }

  public List<TableField> getTableFields(String currentTableName) {
    String[] keyStore = new String[1];
    List<TableField> tableFields = new ArrayList<>();
    FieldWarpper fieldWarpper = new OracleFieldWarpper();
    String keyQuery = String.format("select cu.COLUMN_NAME from user_cons_columns cu, " +
        "user_constraints au,user_tab_columns c where cu.constraint_name = au.constraint_name and c.COLUMN_NAME = cu.column_name" +
        " and c.TABLE_NAME = cu.table_name and au.constraint_type = 'P' and au.table_name = '%s'", currentTableName);
    String query = String.format("select t.COLUMN_NAME,t.DATA_TYPE,t.NULLABLE from user_tab_columns t, " +
        "user_col_comments c where t.table_name = c.table_name " +
        "and t.column_name = c.column_name and t.table_name = '%s' order by t.COLUMN_ID", currentTableName);
    crudInstance.queryAsRow(keyQuery, rs -> keyStore[0] = rs.getString(1));
    crudInstance.eachRow(query, rs -> {
      TableField tableField = fieldWarpper.warpperd(rs);
      if (tableField.getFieldText().equals(keyStore[0])) {
        tableField.setKey("Id");
      } else {
        tableField.setKey("Basic");
      }
      tableFields.add(tableField);
    });
    return tableFields;
  }

}
